/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.web.misc.cg.descriptor;

import org.vacoor.nothing.common.util.StringUtils;

/**
 * Many To Many 关联
 *
 * @author vacoor
 */
public class ManyToMany extends ToMany {
    private JoinTable joinTable;

    public ManyToMany(String source) {
        super(source);
    }

    public JoinTable getJoinTable() {
        return joinTable;
    }

    public void setJoinTable(JoinTable joinTable) {
        this.joinTable = joinTable;
    }

    /**
     * 获取计算后的关联表
     */
    public JoinTable getComputedJoinTable() {
        JoinTable join = null;
        // 关系由对方维护
        if (StringUtils.hasText(mappedBy)) {
            // 查找关系维护方中的当前关联配置
            for (ManyToMany manyToMany : rel.getManyToMany()) {
                if (mappedBy.equals(manyToMany.getProperty())) {
                    JoinTable jt = manyToMany.getJoinTable();
                    join = new JoinTable();
                    join.setName(jt.getName());
                    join.setJoinColumn(jt.getInverseJoinColumn());
                    join.setInverseJoinColumn(jt.getJoinColumn());
                    break;
                }
            }
            //
            if (null == join) {
                throw new IllegalArgumentException(property + "标注为 ManyToMany mappedBy=" + mappedBy + "" + ", 但是不能在" + rel.getFullTypeName() + "中发现 ManyToMany 属性:" + mappedBy + " @" + source);
            }
        } else {
            JoinTable jt = getJoinTable();
            join = new JoinTable();
            join.setName(jt.getName());
            join.setJoinColumn(jt.getJoinColumn());
            join.setInverseJoinColumn(jt.getInverseJoinColumn());
        }
        return join;
    }
}
